/* 
 * VelocityUtil.java 
 * 
 * Copyright 2009 Handlewell Beijing Inc. 
 * All rights reserved. 
 * 
 * Created on 2009-8-24 
 */
package com.handlewell.generator.support;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Properties;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;

/**
 * 功能概述： <br>
 * 
 * @author 倪敏
 */
public class VelocityUtil {
	/** 静态变量 */
	private static int BUFFER_SIZE = 1024;

	/** 容器 */
	private VelocityContext context = null;

	/** 模板 */
	private Template template = null;


	/**
	 * 初始化容器（修改Velocity的默认配置）
	 */
	public void init() throws Exception {
		Properties props = new Properties();
		// 设置Velocity资源加载方式（默认为file）
		props.setProperty("resource.loader", "class");
		// 加载器实现类
		props.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
		// 设置编码
		props.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
		props.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
		props.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");

		// 修改Velocity默认配置文件中对应的属性，在org.apache.velocity.runtime.defaults包中。
		Velocity.init(props);

		// 初始化容器
		context = new VelocityContext();
	}

	/**
	 * 把模板文件需要使用的对象附加到Velocity容器中。 放进去的数据必须是一个JAVA对象
	 */
	public void put(String key, Object value) {
		context.put(key, value);
	}

	/**
	 * 设置模版文件
	 */
	public void setTemplate(String templateFile, String encoding)throws Exception {
		try {
			template = Velocity.getTemplate(templateFile, encoding);
		} catch (ResourceNotFoundException rnfe) {
			rnfe.printStackTrace();
			throw new Exception("找不到模板：" + templateFile);
		} catch (ParseErrorException pee) {
			throw new Exception("解析模板错误" + templateFile + "：" + pee);
		} catch (Exception e) {
			throw new Exception(e.toString());
		}
	}

	/**
	 * 将输入流转换成字符串
	 */
	public static String getStringFromStream(InputStream is) throws IOException {
		if (null == is)
			return null;
		try {
			InputStreamReader reader = new InputStreamReader(is);
			char[] buffer = new char[BUFFER_SIZE];
			StringWriter writer = new StringWriter();
			int bytes_read;
			while ((bytes_read = reader.read(buffer)) != -1) {
				writer.write(buffer, 0, bytes_read);
			}
			return (writer.toString());
		}
		finally {
			if (null != is) {
				is.close();
			}
		}
	}

	/**
	 * 将模板内容填充数据后输出到文件
	 */
	public void toFile(String path, String fileName) throws Exception {
		try {
			// 用容器中的数据替换模板内容并输出到StringWriter
			StringWriter sw = new StringWriter();
			template.merge(context, sw);

			// 创建目录路径
			File dir = new File(path);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			// 创建文件
			File file = new File(dir.getPath(), fileName);
			// 输出到文件
			FileOutputStream fos = new FileOutputStream(file);
			Writer out = new OutputStreamWriter(fos, "UTF-8");
			out.write(sw.toString());
			out.close();
			fos.close();
//			
//			
//			
//			BufferedWriter out=new BufferedWriter(new FileWriter(file));
//			out.write(sw.toString());
//			out.close();
		}
		catch (Exception e) {
			throw new Exception(e.toString());
		}
	}
}
